/* eslint-disable no-return-assign */
import React, { useState, useEffect, Fragment, useCallback } from 'react';
import { getEmployeeInfoList } from '@/services/components/userform';
import {
    Modal,
    Form,
    // Input,
    // Table,
    // Popconfirm,
    message,
    Radio,
    Select
} from 'antd';
// import { TablePagination } from 'vv-frontend-components';
import { listTemplateAndAgent } from '@/services/flowMine/waitApprovals';
// import DataTable from '@/components/DataTable';
import SimpleDataTable from '@/components/DataTable/SimpleDataTable';
// import Locale from '@/utils/locale';
import request from '@/utils/request';
import { usePrevious } from '@/utils/utils';
import styles from './ProxyModal.less';

const EditableContext = React.createContext();
const { Option } = Select;

const EditableRow = ({ form, index, ...props }) => {
    const [agentEditable, setAgentEditable] = useState(false);
    return (
        <EditableContext.Provider
            value={{
                form,
                agentEditable,
                setAgentEditable: editable => setAgentEditable(editable)
            }}
        >
            <tr {...props} />
        </EditableContext.Provider>
    );
};

const EditableFormRow = Form.create()(EditableRow);

const EditableCell = ({
    editable,
    dataIndex,
    title,
    record = {},
    index,
    handleSave,
    children,
    agentEditable,
    setAgentEditable,
    form,
    ...restProps
}) => {
    const prev = usePrevious(record ? record.agent : '');
    const [options, setOptions] = useState([]);
    const input = React.useRef(null);
    const currentUser = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
    const toggleEdit = () => {
        if (record.isProxy === '1') {
            setAgentEditable(!agentEditable);
        } else {
            setAgentEditable(false);
        }
    };
    const save = value => {
        if (!value) {
            message.error('请设置代理人后提交！');
            input.current.focus();
            return;
        }
        if (prev !== value) {
            form.validateFields((error, values) => {
                if (error) {
                    return;
                }
                toggleEdit();
                const find = options.find(item => item.userCode === values.agent);
                handleSave({
                    ...record,
                    ...values,
                    agentName: find ? find.employeeName : ''
                });
            });
        } else {
            toggleEdit();
        }
    };
    const proxySave = e => {
        if (e.target.value === '0') {
            form.setFieldsValue(
                {
                    agent: ''
                },
                () => {
                    setAgentEditable(false);
                    form.validateFields((error, values) => {
                        handleSave({ ...record, ...values, agentName: '' });
                    });
                }
            );
        } else {
            setAgentEditable(true);
            form.validateFields(['agent']);
            form.validateFields((error, values) => {
                handleSave({ ...record, ...values, agentName: '' });
            });
        }
    };
    const fetchUsers = useCallback(
        async value => {
            if (value) {
                const response = await getEmployeeInfoList({
                    companyId: currentUser.companyId,
                    userName: value
                });

                if (response.code === 10000) {
                    setOptions(response.data.map(item => ({ ...item, userCode: item.employeeCode })));
                }
            }
        },
        [currentUser.companyId]
    );
    const handleSearch = value => {
        if (value) {
            fetchUsers(value);
        } else {
            setOptions([]);
        }
    };

    const renderCell = () => (
        <Fragment>
            <Form.Item
                style={{
                    margin: 0,
                    display: agentEditable ? 'block' : 'none'
                }}
            >
                {form.getFieldDecorator(dataIndex, {
                    rules: [
                        {
                            required: true,
                            message: `请选择${title}！`
                        }
                    ],
                    initialValue: record[dataIndex]
                })(
                    <Select
                        style={{ width: 200 }}
                        ref={input}
                        onPressEnter={save}
                        showSearch
                        defaultActiveFirstOption={false}
                        showArrow={false}
                        filterOption={false}
                        notFoundContent={null}
                        onBlur={save}
                        onSearch={handleSearch}
                    >
                        {options.map(option => (
                            <Option key={option.userCode} value={option.userCode}>
                                {option.employeeName}
                            </Option>
                        ))}
                    </Select>
                )}
            </Form.Item>
            <div
                className="editable-cell-value-wrap"
                style={{
                    height: 30,
                    display: !agentEditable ? 'block' : 'none'
                }}
                onClick={toggleEdit}
            >
                {record.agentName}
            </div>
        </Fragment>
    );
    const renderProxyCell = () => (
        <Form.Item style={{ margin: 0 }}>
            {form.getFieldDecorator(dataIndex, {
                initialValue: record[dataIndex]
            })(
                <Radio.Group onChange={proxySave}>
                    <Radio value="1">是</Radio>
                    <Radio value="0">否</Radio>
                </Radio.Group>
            )}
        </Form.Item>
    );
    useEffect(
        () => () => {
            form.resetFields();
        },
        []
    );
    useEffect(() => {
        if (agentEditable) {
            fetchUsers(record.agentName);
        }
        if (agentEditable && input.current) {
            input.current.focus();
        }
    }, [agentEditable, record.agent]);
    if (dataIndex === 'isProxy') {
        return <td {...restProps}>{renderProxyCell()}</td>;
    }
    return <td {...restProps}>{editable ? renderCell() : children}</td>;
};

const ProxyModal = ({ onOk, form, visible, ...rest }) => {
    const currentUser = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
    const [dataSource, setDataSource] = useState([]);
    const components = {
        body: {
            row: EditableFormRow,
            cell: props => (
                <EditableContext.Consumer>{value => <EditableCell {...props} {...value} />}</EditableContext.Consumer>
            )
        }
    };
    const handleSave = async row => {
        if (!row.agent) return;
        const response = await request('/api/oa/v1/workflow/proxy/assignagentwithtemplate', {
            method: 'POST',
            data: {
                ...row,
                proxyId: row.proxyId !== 'null' ? row.proxyId : ''
            }
        });
        if (response.code === 10000) {
            message.success('保存成功！');
            const newData = [...dataSource];
            const index = newData.findIndex(item => row.proxyId === item.proxyId);
            const item = newData[index];
            newData.splice(index, 1, {
                ...item,
                ...row,
                ...response.data
            });
            console.info('>>>', newData);
            setDataSource(newData);
        } else {
            message.error(response.msg);
        }
    };

    const getData = async ({ pageSize, current }) => {
        if (visible) {
            const response = await listTemplateAndAgent({
                companyId: currentUser.companyId,
                departmentId: currentUser.departmentId,
                employeeCode: currentUser.employeeCode,
                pageNo: current,
                pageSize
            });

            if (response.code === 10000) {
                setDataSource(response.data.rows);
                return {
                    current: response.data.pageNo,
                    pageSize: response.data.pageSize,
                    data: response.data.rows,
                    total: response.data.total
                };
            }
            message.error(response.msg);
            return {
                data: [],
                current: 1,
                pageSize: 10,
                total: 0
            };
        }
        return {
            data: [],
            current: 1,
            pageSize: 10,
            total: 0
        };
    };

    const columns = [
        {
            title: '流程',
            dataIndex: 'templateName',
            key: 'templateName'
        },
        {
            title: '适用公司',
            dataIndex: 'companyName',
            key: 'companyName'
        },
        {
            title: '是否委托代理',
            dataIndex: 'isProxy',
            key: 'isProxy',
            editable: true
        },
        {
            title: '代理人',
            dataIndex: 'agent',
            key: 'agent',
            editable: true
        }
    ].map(col => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: record => ({
                record,
                editable: col.editable,
                dataIndex: col.dataIndex,
                title: col.title,
                handleSave
            })
        };
    });
    return (
        <Modal
            footer={null}
            className={styles.modal}
            title="流程代理设置"
            visible={visible}
            onOk={onOk}
            maskClosable={false}
            {...rest}
        >
            <SimpleDataTable
                fetchData={getData}
                form={form}
                formConfig={{}}
                columns={columns}
                dataSource={dataSource}
                rowKey="id"
                tableProps={{
                    components,
                    style: {
                        marginTop: 0
                    },
                    rowClassName: record => (record.isProxy === '1' ? 'editable-row' : '')
                }}
            >
                {({ table }) => table}
            </SimpleDataTable>
        </Modal>
    );
};

export default Form.create()(ProxyModal);
